import {  
    fetchStepData,  
    fetchTempData,  
    fetchOxygenData,  
    fetchRateData,  
    fetchBpData,
    fetchSleepData
} from '@/services/health';  
import {  
    getBloodPressureStatus,  
    getHeartStatus,  
    getBloodOxygenStatus,  
    getTemperatureStatus,  
    formatTime  
} from './template.js'  
import dayjs from 'dayjs'  
import { getParams, logger } from '@/utils/util'
import { customNavigate } from '@/utils/route'

const colorMapping = {  
    'stepsum': '#53BCF6',  
    'heartrate': '#F88941',  
    'bp': '#ED715D',  
    'bloodoxygen': '#ED715D',  
    'temperature': '#F88941'  
};  

const statusMapping = {  
    'bp': getBloodPressureStatus,  
    'heartrate': getHeartStatus,  
    'bloodoxygen': getBloodOxygenStatus,  
    'temperature': getTemperatureStatus
};  

const fetchMapping = {  
    'stepsum': fetchStepData,  
    'bp': fetchBpData,  
    'heartrate': fetchRateData,  
    'bloodoxygen': fetchOxygenData,  
    'temperature': fetchTempData ,
    'sleep': fetchSleepData 
};  

Page({  
    data: {  
        bgColor: null,  
        pageType: 'stepsum',  
        config: {},  
        date: null,  
        record_list: [],
        sleepData: {}
    },  

    onLoad(options) {  
        const { tag } = getParams(options.params)
        this.setData({  
            bgColor: colorMapping[tag],  
            pageType: tag  
        });  
    },  

    // 日历变化事件  
    onCalendarChange(e) {  
        const stime = `${e.detail.year}-${e.detail.month < 10 ? `0${e.detail.month}` : e.detail.month}-${e.detail.day < 10 ? `0${e.detail.day}` : e.detail.day}`;  
        this.setData({  
            date: `${e.detail.month < 10 ? `0${e.detail.month}` : e.detail.month}.${e.detail.day < 10 ? `0${e.detail.day}` : e.detail.day}`  
        });  

        // 根据 pageType 动态调用对应的渲染函数  
        this.renderChart(stime);  
    },  

    // 渲染图表的通用方法  
    async renderChart(stime) {  
        const { pageType } = this.data;  
        const fetchFunction = fetchMapping[pageType];  

        if (!fetchFunction) {  
            logger.error('未找到对应的数据获取函数！');  
            return;  
        }  

        logger.log(`调用 ${pageType} 图表渲染函数，时间：`, stime);  

        const res = await fetchFunction({ stime });  
        logger.log(`${pageType} 数据：`, res);  
        if(pageType === 'sleep') {
            console.log(res.data)
            this.setData({
                sleepData: {
                    deep_sleep: res.data.deep_sleep,
                    light_sleep: res.data.light_sleep,
                    deeppercent: res.data.deeppercent,
                    lightpercent: res.data.lightpercent
                }
            })
            return;
        }

        // 通用的 xAxis 和 yAxis 配置  
        const xAxis = {  
            type: 'category',  
            data: res.data.list.map(item => dayjs(item.time_begin).format('HH:mm')),  
            axisLine: { lineStyle: { color: '#fff' } }  
        };  

        const yAxis = {  
            type: 'value',  
            axisLabel: { color: '#fff' },  
            splitLine: { lineStyle: { type: 'dashed' } }  
        };  

        // 动态生成 series 数据  
        let series = [];  
        let recordList = [];  
        let yAxisName = '';  

        switch (pageType) {  
            case 'stepsum':  
                yAxisName = `计步 ${res.data.step.stepsum} 步`;  
                series = [{  
                    data: res.data.list.map(item => item.value),  
                    type: 'line',  
                    lineStyle: { color: '#fff' },  
                    itemStyle: { color: '#fff', borderType: 'dotted' }  
                }];  
                break;  

            case 'bp':  
                yAxisName = '血压 (mmHg)';  
                series = [  
                    {  
                        name: 'dbp',  
                        data: res.data.list.map(item => item.dbp),  
                        type: 'line',  
                        lineStyle: { color: '#fff' },  
                        itemStyle: { color: '#fff', borderType: 'dotted' }  
                    },  
                    {  
                        name: 'sbp',  
                        data: res.data.list.map(item => item.sbp),  
                        type: 'line',  
                        lineStyle: { color: '#FAFF00' },  
                        itemStyle: { color: '#FAFF00', borderType: 'dotted' }  
                    }  
                ];  
                recordList = res.data.list.map(item => ({  
                    ...item,  
                    time: formatTime(item.time_begin),  
                    comment: getBloodPressureStatus(item.sbp, item.dbp),  
                    text: `<font style="color: ${colorMapping[pageType]}">${item.sbp}/${item.dbp}</font> mmHg`  
                }));  
                break;  

            case 'heartrate':  
                yAxisName = '心率 (次/分)';  
                series = [{  
                    data: res.data.list.map(item => item.heartrate),  
                    type: 'line',  
                    lineStyle: { color: '#fff' },  
                    itemStyle: { color: '#fff', borderType: 'dotted' }  
                }];  
                recordList = res.data.list.map(item => ({  
                    ...item,  
                    time: formatTime(item.time_begin),  
                    comment: getHeartStatus(item.heartrate),  
                    text: `<font style="color: ${colorMapping[pageType]}">${item.heartrate}</font> 次/分`  
                }));  
                break;  

            case 'bloodoxygen':  
                yAxisName = '血氧 (%)';  
                series = [{  
                    data: res.data.list.map(item => item.bloodoxygen),  
                    type: 'line',  
                    lineStyle: { color: '#fff' },  
                    itemStyle: { color: '#fff', borderType: 'dotted' }  
                }];  
                recordList = res.data.list.map(item => ({  
                    ...item,  
                    time: formatTime(item.time_begin),  
                    comment: getBloodOxygenStatus(item.bloodoxygen),  
                    text: `<font style="color: ${colorMapping[pageType]}">${item.bloodoxygen}</font> %`  
                }));  
                break;  

            case 'temperature':  
                yAxisName = '体温 (℃)';  
                series = [{  
                    data: res.data.list.map(item => item.temperature),  
                    type: 'line',  
                    lineStyle: { color: '#fff' },  
                    itemStyle: { color: '#fff', borderType: 'dotted' }  
                }];  
                recordList = res.data.list.map(item => ({  
                    ...item,  
                    time: formatTime(item.time_begin),  
                    comment: getTemperatureStatus(item.temperature),  
                    text: `<font style="color: ${colorMapping[pageType]}">${item.temperature}</font> ℃`  
                }));  
                break;  
        }  

        // 更新图表和记录列表  
        if(pageType == 'stepsum') {
            this.setData({
                step: res.data.step
            })
        }
        
        this.setData({  
            config: {  
                grid: { right: 20, left: 60, bottom: 20 },  
                xAxis,  
                yAxis: {  
                    ...yAxis,  
                    name: yAxisName,  
                    nameTextStyle: { color: '#fff', fontSize: 18, fontWeight: 'bold' }  
                },  
                series  
            },  
            record_list: recordList
        });  
    },  

    onNavigate(event) {  
        const { item } = event.currentTarget.dataset;  
        const { pageType } = this.data;  
        const params = {
            type: pageType,
            date: item.time_begin,
            status: item.comment.status,
            value: pageType === 'bp' ? `${item.sbp}/${item.dbp}` :  
            pageType === 'bloodoxygen' ? `${item.bloodoxygen}` :  
            pageType === 'heartrate' ? `${item.heartrate}` :  
            pageType === 'temperature' ? `${item.temperature}` : undefined
        }
        customNavigate({
            url: `../Info/index`,
            params  
        });  
    }  
});